# encoding: utf-8
module ApplicationHelper
  
  def parse_bbcode(code, untrusted_source = true)
  	
  	# kompatibilnost s starim postovima i udip-codeom
  	code.gsub!(/\[\/n\]/,'')
  	code.gsub! '[xml]','[code=xml]'
    code.gsub! '[/xml]', '[/code]'

		# new line to <br> i HTML escape
		# (treba pazid da se ne stavlja <br> unutar [code] blockova)  	
  	sliced_code = code.split(/\[code=.*?\]|\[\/code\]/mi)
		
		new_lines_to_br = true  	
  	sliced_code.each do |slice|
  		
  		# ako je dio posta koji nije unutar code blocka stripaj HTML tagove i pretvori nl2br
  		if new_lines_to_br
  			if untrusted_source
  				code[slice] = slice.gsub(/<\/?[^>]*>/, "").gsub(/\n/,'<br />')
  			end
  		# inace zamjeni < > kako bi se HTML kod prikazao, a ne parsirao
  		else
  			code[slice] = slice.gsub('<','&lt;').gsub('>','&gt;')
  		end
  		new_lines_to_br = ! new_lines_to_br
  	end
  	
  	# bold
  	code.gsub!(/\[b\](.*?)\[\/b\]/mi,'<b>\1</b>')
  	
  	# italic
  	code.gsub!(/\[i\](.*?)\[\/i\]/mi,'<i>\1</i>')
  	
  	# code
  	code.gsub!(/\[code=(.*?)\](.*?)\[\/code\]/mi,'<pre class="brush: \1">\2</pre>')

  	#quote
  	code.gsub!(/\[quote(:.*)?\](.*?)\[\/quote\1?\]/mi,'<div class="quote"><blockquote>\2</blockquote></div>')
  	code.gsub!(/\[quote(:.*)?=(.*?)\](.*?)\[\/quote\1?\]/mi,'<div class="quote"><div class="cite-name">\2 je rekao:</div><blockquote>\3</blockquote></div>')

		#link
		if untrusted_source
			code.gsub!(/\[url=(.*?)\](.*?)\[\/url\]/mi,'<a href="\1" target="_blank" rel="nofollow">\2</a>')
			code.gsub!(/\[url\](.*?)\[\/url\]/mi,'<a href="\1" target="_blank" rel="nofollow">\1</a>')
		else
			code.gsub!(/\[url=(.*?)\](.*?)\[\/url\]/mi,'<a href="\1" target="_blank">\2</a>')
			code.gsub!(/\[url\](.*?)\[\/url\]/mi,'<a href="\1" target="_blank">\1</a>')
		end
		

		#img
		code.gsub!(/\[img\](.*?)\[\/img\]/mi,'<img src="\1">')

		#base_url
    code.gsub! '{root_url}', root_url
    code.gsub! '{base_url}', root_url

  	return code
  end
  
  def paginate(items)
  	return will_paginate items, :previous_label => "← prethodna", :next_label => "sljedeća →"
  end
  
  def logged?
  	
  	return (current_member != nil)
  	
  end
  
  def approved?
  	
  	if current_member != nil
  		if current_member.is_approved?
  			reutrn true
  		end
  	end
  	
  	return false
  	
  end
  
  def moderator?
    
    if current_member != nil
      if current_member.is_moderator?
        return true
      end
    end
    
    return false
  end
  
  def admin?
  	if current_member != nil
  		if current_member.is_admin?
  			return true
  		end
  	end
  	
  	return false
  end
  
  
  def moderator_or_this_member?(user_id)
    if current_member != nil
      if current_member.is_moderator? || current_member.id == user_id
        return true
      end
    end
  end
end
